package com.retail.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.retail.common.exception.BusinessException;
import com.retail.common.result.ResultCode;
import com.retail.product.dto.ProductAddDTO;
import com.retail.product.dto.ProductAddResponseDTO;
import com.retail.product.dto.ProductQueryDTO;
import com.retail.product.entity.Product;
import com.retail.product.entity.ProductSku;
import com.retail.product.entity.ProductImage;
import com.retail.product.mapper.ProductMapper;
import com.retail.product.service.ProductService;
import com.retail.product.vo.ProductVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 商品服务实现类
 *
 * @author retail
 * @since 2024-09-25
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    private final ProductMapper productMapper;

    @Override
    public IPage<ProductVO> getProductPage(Page<ProductVO> page, ProductQueryDTO queryDTO) {
        return productMapper.selectProductPage(page, queryDTO);
    }

    @Override
    public ProductVO getProductById(Long id) {
        if (id == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "商品ID不能为空");
        }
        return productMapper.selectProductById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProductAddResponseDTO addProduct(ProductAddDTO productAddDTO) {
        log.info("开始添加商品，商品名称：{}", productAddDTO.getName());
        
        // 1. 创建商品基本信息
        Product product = new Product();
        BeanUtil.copyProperties(productAddDTO, product);
        product.setStatus(1); // 默认上架
        product.setSortOrder(0);
        product.setCreatedTime(LocalDateTime.now());
        product.setUpdatedTime(LocalDateTime.now());
        
        // 保存商品基本信息
        int saveResult = productMapper.insert(product);
        if (saveResult <= 0) {
            throw new BusinessException(ResultCode.INTERNAL_SERVER_ERROR.getCode(), "商品保存失败");
        }
        
        Long productId = product.getId();
        log.info("商品基本信息保存成功，商品ID：{}", productId);
        
        // 2. 创建商品SKU
        ProductSku productSku = new ProductSku();
        productSku.setProductId(productId);
        productSku.setSkuCode(generateSkuCode(productId));
        productSku.setSkuName(productAddDTO.getName());
        productSku.setPrice(productAddDTO.getPrice());
        productSku.setCostPrice(productAddDTO.getCostPrice());
        productSku.setStockQuantity(productAddDTO.getStockQuantity() != null ? productAddDTO.getStockQuantity() : 0);
        productSku.setLowStockThreshold(productAddDTO.getLowStockThreshold() != null ? productAddDTO.getLowStockThreshold() : 0);
        productSku.setWeight(productAddDTO.getWeight());
        productSku.setVolume(productAddDTO.getVolume());
        productSku.setStatus(1);
        productSku.setCreatedTime(LocalDateTime.now());
        productSku.setUpdatedTime(LocalDateTime.now());
        
        int skuResult = productMapper.insertProductSku(productSku);
        if (skuResult <= 0) {
            throw new BusinessException(ResultCode.INTERNAL_SERVER_ERROR.getCode(), "商品SKU保存失败");
        }
        log.info("商品SKU保存成功，SKU ID：{}", productSku.getId());
        
        // 3. 保存商品图片
        if (productAddDTO.getImages() != null && !productAddDTO.getImages().isEmpty()) {
            List<ProductImage> images = new ArrayList<>();
            for (ProductAddDTO.ProductImageDTO imageDTO : productAddDTO.getImages()) {
                ProductImage productImage = new ProductImage();
                productImage.setProductId(productId);
                productImage.setImageUrl(imageDTO.getImageUrl());
                productImage.setImageType(imageDTO.getImageType() != null ? imageDTO.getImageType() : 1);
                productImage.setSortOrder(imageDTO.getSortOrder() != null ? imageDTO.getSortOrder() : 0);
                productImage.setCreatedTime(LocalDateTime.now());
                images.add(productImage);
            }
            
            int imageResult = productMapper.insertProductImages(images);
            if (imageResult <= 0) {
                throw new BusinessException(ResultCode.INTERNAL_SERVER_ERROR.getCode(), "商品图片保存失败");
            }
            log.info("商品图片保存成功，共保存{}张图片", images.size());
        }
        
        // 4. 构建响应对象
        ProductAddResponseDTO responseDTO = new ProductAddResponseDTO();
        BeanUtil.copyProperties(product, responseDTO);
        
        log.info("商品添加完成，商品ID：{}", productId);
        return responseDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateProduct(Long id, Product product) {
        if (id == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "商品ID不能为空");
        }
        
        // 校验商品是否存在
        Product existProduct = productMapper.selectById(id);
        if (existProduct == null) {
            throw new BusinessException(ResultCode.DATA_NOT_EXIST.getCode(), "商品不存在");
        }
        
        product.setId(id);
        product.setUpdatedTime(LocalDateTime.now());
        
        return productMapper.updateById(product) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteProduct(Long id) {
        if (id == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "商品ID不能为空");
        }
        
        // 校验商品是否存在
        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new BusinessException(ResultCode.DATA_NOT_EXIST.getCode(), "商品不存在");
        }
        
        return productMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteProducts(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "商品ID列表不能为空");
        }
        
        log.info("批量删除商品，IDs: {}", ids);
        
        // 批量删除
        int deleteCount = productMapper.deleteBatchIds(ids);
        
        log.info("批量删除商品完成，删除数量: {}", deleteCount);
        return deleteCount > 0;
    }

    /**
     * 生成SKU编码
     *
     * @param productId 商品ID
     * @return SKU编码
     */
    private String generateSkuCode(Long productId) {
        return "SKU" + productId + "_" + IdUtil.fastSimpleUUID().substring(0, 8).toUpperCase();
    }
}
